package com.quan.system.web.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quan.common.bean.ResultBean;
import com.quan.common.bean.WebSocketMessage;
import com.quan.common.core.MyBaseController;

/**
 * WebSocket 前端控制器
 * 提供给前端调用
 * @author yhaoquan
 *
 */
@RestController
@RequestMapping("/websocket")
public class WebSocketSockJSController extends MyBaseController {
	
	@Autowired
	private SimpMessagingTemplate messagingTemplate ;
	
	/**
	 * 前端SockJS连接，成功返回信息给客户端
	 * @return
	 */
	@SubscribeMapping(value = "/notification")
	public String notification() {
		return "欢迎订阅【系统消息功能】" ;
	}
	
	/**
	 * 广播系统消息
	 * @param message
	 */
	@PostMapping(value = "/notification")
	public Object notification(@RequestBody WebSocketMessage message) {
		logger.info("WebSocket广播系统消息：{}", message);
		this.messagingTemplate.convertAndSend("/topic/notification", JSON.toJSONString(message));
		return ResultBean.ok("消息已发送") ;
	}
	
	/**
	 * 给指定用户发送消息
	 * @param message
	 */
	@PostMapping(value = "/toUser")
	public Object toUser(@RequestBody WebSocketMessage message) {
		logger.info("WebSocket给用户发送消息：{}", message);
		
		if(StringUtils.isNotBlank(message.getTo())) {
			String[] tos = message.getTo().split(",");
			for (String to : tos) {
				this.messagingTemplate.convertAndSendToUser(to, "/message", JSON.toJSONString(message));
			}
			return ResultBean.ok("消息已发送") ;
		} else {
			return ResultBean.failure("消息发送失败") ;
		}
	}
	
	
}
